<?php
/**
 * Created by PhpStorm.
 * User: zzw
 * Date: 17-4-14
 * Time: 上午9:03
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class notify extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('pay_logs_model', 'mpay_log');
        $this->load->model('account_model','maccount');
        $this->load->model('balance_detail_model','mbalance');
        $this->load->model('need_order_model','mneedorder');
        $this->load->model('need_apply_model','mneedapply');
        $this->load->model('needs_model','mneeds');
        $this->load->model('claim_model','mclaim');
        $this->load->model('long_article_model', 'mlarticle');
        $this->load->model('text_zan_model', 'mtzan');
        $this->load->model('countdown_model','mcount_down');

    }

    /**
     * app阿里云支付回调
     */
    public function aliApi()
    {
        require_once(LIBS_PATH . "alipay_api/alipay.config.php");
        require_once(LIBS_PATH . "alipay_api/lib/alipay_notify.class.php");
        require_once(LIBS_PATH . "alipay_api/lib/alipay_rsa.function.php");
        require_once(LIBS_PATH . "alipay_api/lib/alipay_core.function.php");
        $alipayNotify = new AlipayNotify($alipay_config);
        if ($alipayNotify->getResponse($_POST['notify_id']))//判断成功之后使用getResponse方法判断是否是支付宝发来的异步通知。
        {
            if ($alipayNotify->getSignVeryfy($_POST, $_POST['sign'])) {//使用支付宝公钥验签
                //验证成功
                //商户订单号
                $out_trade_no = $_POST['out_trade_no'];
                //支付宝交易号
                $trade_no = $_POST['trade_no'];
                //交易状态
                $trade_status = $_POST['trade_status'];
                if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
                    list($type, $trade) = explode('-', $out_trade_no);
                    try {
                        switch ($type) {
                            case 'S':
                                $order_info = $this->mneeds->get_one(array('order_sn' => $out_trade_no, 'status' => 0));
                                logfile('alipay处理订单为' . json_encode($order_info), 'salipay');
                                if ($order_info) {
                                    logfile('alipay：开始处理支付');
                                    $this->ali_update_order($order_info['id'], $trade_no, $type);
                                }
                                break;
                            case 'E':
                                $order_info = $this->mneedorder->get_one(array('pay_code' => $out_trade_no, 'status' => 0));
                                logfile('alipay处理订单为' . json_encode($order_info), 'ealipay');
                                if ($order_info) {
                                    logfile('alipay：开始处理支付');
                                    $this->ali_update_order($order_info['id'], $trade_no, $type);
                                }
                                break;
                            case 'L':
                                $order_info = $this->mpay_log->get_one(array('pay_code' => $out_trade_no, 'status' => 0));
                                logfile('alipay处理订单为' . json_encode($order_info), 'lalipay');
                                if ($order_info) {
                                    logfile('alipay：开始处理支付');
                                    $this->ali_update_order($order_info['id'], $trade_no, $type);
                                }
                                break;
                            case 'C':
                                $order_info = $this->mpay_log->get_one(array('pay_code' => $out_trade_no, 'status' => 0));
                                logfile('alipay处理订单为' . json_encode($order_info), 'calipay');
                                if ($order_info) {
                                    logfile('alipay：开始处理支付');
                                    $this->ali_update_order($order_info['id'], $trade_no, $type);
                                }
                                break;
                        }
                    } catch (Exception $e) {
                        logfile($e, 'alipay');
                    }
                }
            }
        }
    }
    /**
     *app微信支付回调
     */
    public function wxApi() {
        logfile('微信支付-回掉开始:', 'wxpay');
        include_once LIBS_PATH . 'wxpay/pay_notify.php';
    }

    //微信支付回掉
    public function do_pay_wechat($result){
        logfile('do_pay_wechat微信支付 result:', 'wxpay');
        logfile(json_encode($result), 'wxpay');
        // 处理
        //订单号
        $out_trade_no = $result['out_trade_no'];
        //微信交易号
        $trade_no = $result['transaction_id'];
        $strings = explode('-',$out_trade_no);
        $c_type = $strings[0];
        if($c_type=='S'){
            $order_info=$this->mneeds->get_one(array('order_sn'=>$out_trade_no,'status'=>0));
            logfile('处理订单为'.json_encode($order_info),'swxpay');
            if($order_info){
                logfile('微信支付：开始处理支付');
                $this->wx_update_order($order_info['id'],$trade_no,$c_type);
            }
        }elseif($c_type=='E'){
            $order_info=$this->mneedorder->get_one(array('pay_code'=>$out_trade_no,'status'=>0));
            logfile('处理订单为'.json_encode($order_info),'ewxpay');
            if($order_info){
                logfile('微信支付：开始处理支付');
                $this->wx_update_order($order_info['id'],$trade_no,$c_type);
            }
        }elseif($c_type=='L'){
            $order_info=$this->mpay_log->get_one(array('pay_code'=>$out_trade_no,'status'=>0));
            logfile('处理订单为'.json_encode($order_info),'lwxpay');
            if($order_info){
                logfile('微信支付：开始处理支付');
                $this->wx_update_order($order_info['id'],$trade_no,$c_type);
            }
        }elseif($c_type=='C'){
            $order_info=$this->mpay_log->get_one(array('pay_code'=>$out_trade_no,'status'=>0));
            logfile('处理订单为'.json_encode($order_info),'cwxpay');
            if($order_info){
                logfile('微信支付：开始处理支付');
                $this->wx_update_order($order_info['id'],$trade_no,$c_type);
            }
        }

    }

    /**********微信支付模块*************/
    //悬赏任务支付押金
    public function wx_update_order($oid,$trand_no,$c_type){
        if($c_type=='S'){
            logfile('开始处理','spay');
            $order_info=$this->mneeds->get_one($oid);
            $uid=$order_info['uid'];
            //开启事务处理
            $this->db->trans_begin();
            logfile('进入事务处理处理','spay');
            //添加一条支付明细记录
            //悬赏支出
            $time = time();
            $balance_data_out = array(
                'uid'=>$uid,
                'type'=>3,                                  //悬赏发布押金
                'need_id'=>$oid,
                'title'=>$order_info['intro'],
                'money'=>$order_info['margin'],
                'status'=>2,   //冻结
                'pay_ways'=>1,   //微信
                'pay_time'=>$time,
                'created_at'=>$time,
                'rid'=>0,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['order_sn'],
            );
            $this->mbalance->create($balance_data_out);
            //修改订单状态
            //获取后台的倒计时设置时间
            $count_down = $this->mcount_down->get_one(array('id'=>1));
            $countdown = $time + $count_down['hours']*3600;
            $order_update_data=array('status'=>1,'claim_status'=>1,'countdown'=>$countdown,'pay_time'=>time(),'updated'=>time(),'payment_sn'=>$trand_no);
            $where=array('id'=>$oid);
            $this->mneeds->update($order_update_data,$where);
            logfile('订单修改完成','spay');
            if($this->db->trans_status()===false){
                $this->db->trans_rollback();
                $str='用户id:'.$uid.'的订单'.$order_info['order_sn'].'修改支付状态失败';
                logfile($str,'spay');
            }else{
                $this->db->trans_commit();
                $str='用户id:'.$uid.'的订单'.$order_info['order_sn'].'修改支付状态成功';
                logfile($str,'spay');
                echo "success";
            }
        }elseif($c_type=='E'){
            logfile('开始处理','epay');
            $order_info=$this->mneedorder->get_one($oid);
            $uid=$order_info['uid'];
            //开启事务处理(指派操作订单处理)
            $this->db->trans_begin();
            logfile('进入事务处理处理','epay');
            //添加一条支付明细记录
            //差价支出明细
            $need_info = $this->mneeds->get_one(array('id'=>$order_info['need_id']));
            $balance_data_out1 = array(
                'uid'=>$uid,
                'type'=>4,    //指派补差价
                'need_id'=>$need_info['id'],
                'title'=>$need_info['intro'],
                'money'=>$order_info['money'],
                'status'=>7,   //差价冻结
                'pay_ways'=>1,  //微信支付
                'pay_time'=>time(),
                'created_at'=>time(),
                'rid'=>0,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['pay_code'],
            );
            $this->mbalance->create($balance_data_out1);
            //修改订单状态//差价冻结
            $order_update_data=array('status'=>1,'pay_time'=>time(),'payment_sn'=>$trand_no);
            $where=array('id'=>$oid);
            $this->mneedorder->update($order_update_data,$where);
            $claim_info = $this->mclaim->get_one(array('id'=>$order_info['claim_id']));
            //更新订单为已指派状态
            $this->mneeds->update(array('claim_status'=>3,'claim_money'=>$claim_info['money']),array('id'=>$need_info['id']));
            $this->mclaim->update(array('is_assign'=>1,'update_time'=>time()),array('id'=>$claim_info['id']));
            /*******添加推送板块**********/
            $to_uid = $claim_info['uid'];
            $t_user_info = $this->maccount->get_one(array('id'=>$need_info['uid']));
            $uname = $t_user_info['uname'];
            $t_type = 1;
            $content = '您已被'.$uname.'指派任务';
            getui_push($to_uid,$t_type,$claim_info['need_id'],$content);

            logfile('订单修改完成','epay');
            if($this->db->trans_status()===false){
                $this->db->trans_rollback();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态失败';
                logfile($str,'epay');
            }else{
                $this->db->trans_commit();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态成功';
                logfile($str,'epay');
                echo "success";
            }
        }elseif($c_type=='L'){
            //长文章打赏
            logfile('开始处理','lpay');
            $order_info=$this->mpay_log->get_one($oid);
            $uid=$order_info['uid'];
            //开启事务处理
            $this->db->trans_begin();
            logfile('进入事务处理处理','lpay');
            //获取长文章作者的信息
            $larticle_info = $this->mlarticle->get_one(array('id'=>$order_info['tid'],'is_deleted'=>0));
            $larticle_id = $larticle_info['id'];
            $to_uid = $larticle_info['uid'];
            $money = $order_info['money'];
            $money = (int)$money;
            //文章作者获得赞赏金额
            $this->db->query("update boc_account set balance=balance+$money,zan_money=zan_money+$money where id=$to_uid");
            //赞赏支出
            $balance_data_out = array(
                'uid'=>$uid,
                'type'=>1,                          //赞赏支出
                'title'=>$larticle_info['title'],
                'money'=>$money,
                'status'=>1,
                'pay_ways'=>1,
                'pay_time'=>time(),
                'created_at'=>time(),
                'rid'=>$to_uid,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['pay_code'],
            );
            $this->mbalance->create($balance_data_out);
            //赞赏收入
            $balance_data_in = array(
                'uid'=>$to_uid,
                'type'=>2,                          //赞赏收入
                'title'=>$larticle_info['title'],
                'money'=>$money,
                'status'=>1,
                'pay_ways'=>3,
                'pay_time'=>time(),
                'created_at'=>time(),
                'rid'=>$uid,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['pay_code'],
            );
            $this->mbalance->create($balance_data_in);
            $zan_data = array(
                'uid'=>$uid,
                'tid'=>$order_info['tid'],
                'money'=>$money,
                'created'=>time()
            );
            $this->mtzan->create($zan_data);
            $this->db->query("update boc_long_article set zans=zans+1,zan_money=zan_money+$money where id=$larticle_id");
            //修改订单状态
            $order_update_data=array('status'=>1,'pay_time'=>time(),'payment_sn'=>$trand_no);
            $where=array('id'=>$oid);
            $this->mpay_log->update($order_update_data,$where);
            /*******添加推送板块**********/
            $t_user_info = $this->maccount->get_one(array('id'=>$uid));
            $uname = $t_user_info['uname'];
            $t_type = 3;
            $content = $uname.'赞赏了您';
            getui_push($to_uid,$t_type,$larticle_id,$content);
            logfile('订单修改完成','lpay');
            if($this->db->trans_status()===false){
                $this->db->trans_rollback();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态失败';
                logfile($str,'lpay');
            }else{
                $this->db->trans_commit();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态成功';
                logfile($str,'lpay');
                echo "success";
            }
        }elseif($c_type=='C'){
            //充值处理
            logfile('开始处理','cpay');
            $order_info=$this->mpay_log->get_one($oid);
            $uid=$order_info['uid'];
            //开启事务处理
            $this->db->trans_begin();
            logfile('进入事务处理处理','cpay');
            $money = $order_info['money'];
            //$money = 100;
            //充值到余额
            $this->db->query("update boc_account set balance=balance+$money where id=$uid");
            $balance_data_in = array(
                'uid'=>$uid,
                'type'=>9,                          //充值
                'title'=>'余额充值',
                'money'=>$money,
                'status'=>1,
                'pay_ways'=>1,
                'pay_time'=>time(),
                'created_at'=>time(),
                'rid'=>0,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['pay_code'],
            );
            $this->mbalance->create($balance_data_in);
            //修改订单状态
            $order_update_data=array('status'=>1,'pay_time'=>time(),'payment_sn'=>$trand_no);
            $where=array('id'=>$oid);
            $this->mpay_log->update($order_update_data,$where);
            logfile('订单修改完成','cpay');
            if($this->db->trans_status()===false){
                $this->db->trans_rollback();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态失败';
                logfile($str,'cpay');
            }else{
                $this->db->trans_commit();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态成功';
                logfile($str,'cpay');
                echo "success";
            }
        }

    }

    public function ali_update_order($oid,$trand_no,$c_type){
        if($c_type=='S'){
            logfile('开始处理','spay');
            $order_info=$this->mneeds->get_one($oid);
            $uid=$order_info['uid'];
            //开启事务处理
            $this->db->trans_begin();
            logfile('进入事务处理处理','spay');
            //添加一条支付明细记录
            //悬赏支出
            $time = time();
            $balance_data_out = array(
                'uid'=>$uid,
                'type'=>3,                                  //悬赏发布押金
                'need_id'=>$oid,
                'title'=>$order_info['intro'],
                'money'=>$order_info['margin'],
                'status'=>2,   //冻结
                'pay_ways'=>2,   //支付宝
                'pay_time'=>$time,
                'created_at'=>$time,
                'rid'=>0,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['order_sn'],
            );
            $this->mbalance->create($balance_data_out);
            //修改订单状态
            $count_down = $this->mcount_down->get_one(array('id'=>1));
            $countdown = $time + $count_down['hours']*3600;
            $order_update_data=array('status'=>1,'claim_status'=>1,'countdown'=>$countdown,'pay_time'=>time(),'updated'=>time(),'payment_sn'=>$trand_no);
            $where=array('id'=>$oid);
            $this->mneeds->update($order_update_data,$where);
            logfile('订单修改完成','spay');
            if($this->db->trans_status()===false){
                $this->db->trans_rollback();
                $str='用户id:'.$uid.'的订单'.$order_info['order_sn'].'修改支付状态失败';
                logfile($str,'spay');
            }else{
                $this->db->trans_commit();
                $str='用户id:'.$uid.'的订单'.$order_info['order_sn'].'修改支付状态成功';
                logfile($str,'spay');
                echo "success";
            }
        }elseif($c_type=='E'){
            logfile('开始处理','epay');
            $order_info=$this->mneedorder->get_one($oid);
            $uid=$order_info['uid'];
            //开启事务处理(指派操作订单处理)
            $this->db->trans_begin();
            logfile('进入事务处理处理','epay');
            //添加一条支付明细记录
            //差价支出明细
            $need_info = $this->mneeds->get_one(array('id'=>$order_info['need_id']));
            $balance_data_out1 = array(
                'uid'=>$uid,
                'type'=>4,    //指派补差价
                'need_id'=>$need_info['id'],
                'title'=>$need_info['intro'],
                'money'=>$order_info['money'],
                'status'=>7,   //差价冻结
                'pay_ways'=>2,   //支付宝
                'pay_time'=>time(),
                'created_at'=>time(),
                'rid'=>0,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['pay_code'],
            );
            $this->mbalance->create($balance_data_out1);
            //修改订单状态//差价冻结
            $order_update_data=array('status'=>1,'pay_time'=>time(),'payment_sn'=>$trand_no);
            $where=array('id'=>$oid);
            $this->mneedorder->update($order_update_data,$where);
            $claim_info = $this->mclaim->get_one(array('id'=>$order_info['claim_id']));
            //更新订单为已指派状态
            $this->mneeds->update(array('claim_status'=>3,'claim_money'=>$claim_info['money']),array('id'=>$need_info['id']));
            $this->mclaim->update(array('is_assign'=>1,'update_time'=>time()),array('id'=>$claim_info['id']));

            /*******添加推送板块**********/
            $to_uid = $claim_info['uid'];
            $t_user_info = $this->maccount->get_one(array('id'=>$need_info['uid']));
            $uname = $t_user_info['uname'];
            $t_type = 1;
            $content = '您已被'.$uname.'指派任务';
            getui_push($to_uid,$t_type,$claim_info['need_id'],$content);
            logfile('订单修改完成','epay');
            if($this->db->trans_status()===false){
                $this->db->trans_rollback();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态失败';
                logfile($str,'epay');
            }else{
                $this->db->trans_commit();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态成功';
                logfile($str,'epay');
                echo "success";
            }
        }elseif($c_type=='L'){
            //长文章打赏
            logfile('开始处理','lpay');
            $order_info=$this->mpay_log->get_one($oid);
            $uid=$order_info['uid'];
            //开启事务处理
            $this->db->trans_begin();
            logfile('进入事务处理处理','lpay');
            //获取长文章作者的信息
            $larticle_info = $this->mlarticle->get_one(array('id'=>$order_info['tid'],'is_deleted'=>0));
            $larticle_id = $larticle_info['id'];
            $to_uid = $larticle_info['uid'];
            $money = $order_info['money'];
            $money = (int)$money;
            //文章作者获得赞赏金额
            $this->db->query("update boc_account set balance=balance+$money,zan_money=zan_money+$money where id=$to_uid");
            //赞赏支出
            $balance_data_out = array(
                'uid'=>$uid,
                'type'=>1,                          //赞赏支出
                'title'=>$larticle_info['title'],
                'money'=>$money,
                'status'=>1,
                'pay_ways'=>2,   //支付宝
                'pay_time'=>time(),
                'created_at'=>time(),
                'rid'=>$to_uid,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['pay_code'],
            );
            $this->mbalance->create($balance_data_out);
            //赞赏收入
            $balance_data_in = array(
                'uid'=>$to_uid,
                'type'=>2,                          //赞赏收入
                'title'=>$larticle_info['title'],
                'money'=>$money,
                'status'=>1,
                'pay_ways'=>3,
                'pay_time'=>time(),
                'created_at'=>time(),
                'rid'=>$uid,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['pay_code'],
            );
            $this->mbalance->create($balance_data_in);
            $zan_data = array(
                'uid'=>$uid,
                'tid'=>$order_info['tid'],
                'money'=>$money,
                'created'=>time()
            );
            $this->mtzan->create($zan_data);
            $this->db->query("update boc_long_article set zans=zans+1,zan_money=zan_money+$money where id=$larticle_id");
            //修改订单状态
            $order_update_data=array('status'=>1,'pay_time'=>time(),'payment_sn'=>$trand_no);
            $where=array('id'=>$oid);
            $this->mpay_log->update($order_update_data,$where);

            /*******添加推送板块**********/
            $t_user_info = $this->maccount->get_one(array('id'=>$uid));
            $uname = $t_user_info['uname'];
            $t_type = 3;
            $content = $uname.'赞赏了您';
            getui_push($to_uid,$t_type,$larticle_id,$content);
            logfile('订单修改完成','lpay');
            if($this->db->trans_status()===false){
                $this->db->trans_rollback();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态失败';
                logfile($str,'lpay');
            }else{
                $this->db->trans_commit();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态成功';
                logfile($str,'lpay');
                echo "success";
            }
        }elseif($c_type=='C'){
            //充值处理
            logfile('开始处理','cpay');
            $order_info=$this->mpay_log->get_one($oid);
            $uid=$order_info['uid'];
            //开启事务处理
            $this->db->trans_begin();
            logfile('进入事务处理处理','cpay');
            $money = $order_info['money'];
            //$money = 100;
            //充值到余额
            $this->db->query("update boc_account set balance=balance+$money where id=$uid");
            $balance_data_in = array(
                'uid'=>$uid,
                'type'=>9,                          //充值
                'title'=>'余额充值',
                'money'=>$money,
                'status'=>1,
                'pay_ways'=>2,   //支付宝
                'pay_time'=>time(),
                'created_at'=>time(),
                'rid'=>0,
                'payment_sn'=>$trand_no,
                'pay_code'=>$order_info['pay_code'],
            );
            $this->mbalance->create($balance_data_in);
            //修改订单状态
            $order_update_data=array('status'=>1,'pay_time'=>time(),'payment_sn'=>$trand_no);
            $where=array('id'=>$oid);
            $this->mpay_log->update($order_update_data,$where);
            logfile('订单修改完成','cpay');
            if($this->db->trans_status()===false){
                $this->db->trans_rollback();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态失败';
                logfile($str,'cpay');
            }else{
                $this->db->trans_commit();
                $str='用户id:'.$uid.'的订单'.$order_info['pay_code'].'修改支付状态成功';
                logfile($str,'cpay');
                echo "success";
            }
        }

    }
    //阿里批量付款回调
    public function Alibatch() {
        require_once(LIBS_PATH."alipay_batch/alipay.config.php");
        require_once(LIBS_PATH."alipay_batch/lib/alipay_notify.class.php");

        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        logfile('verify_result：'.json_encode($verify_result),'Alibatch');
        if($verify_result) {//验证成功
            logfile('$_POST：'.print_r($_POST,1),'Alibatch');
            $success_details = $_POST['success_details'];
            logfile('success_details：'.print_r($success_details,1),'Alibatch');
            if($success_details) {
                //批量付款数据中转账失败的详细信息
                $arr = explode('^',$success_details);
                $trade_sn = $arr[6];
                $arr = explode('-',$arr[0]);
                //$partner_trade_no = $arr[1];
                $this->load->model('withdrawapply_model','mwithdrawapply');
                $this->load->model('balance_detail_model','mbalance_detail');
                $batch = $this->mwithdrawapply->get_one(array('partner_trade_no'=>$arr[1]));
                $balance = $this->mbalance_detail->get_one(array('pay_code'=>$arr[1]));
                $this->mwithdrawapply->set($batch['id'],array('is_checked'=>1,'updated'=>time(),'finished'=>time(),'response'=>$success_details,'trade_sn'=>$trade_sn));
                $this->mbalance_detail->set($balance['id'],array('status'=>1,'updated_at'=>time(),'response'=>$success_details,'payment_sn'=>$trade_sn));
            }

            echo "success";		//请不要修改或删除
        } else {
            $fail_details = $_POST['fail_details'];
            logfile('fail_details：'.print_r($fail_details,1),'Alibatch');
            echo "fail";
        }
    }
}